package org.netty.buffers;

import java.nio.charset.Charset;
import java.util.Random;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;

public class ByteBufTest {
	
	public static void main(String[] args) {
//		Random random = new Random();
//		
//		ByteBuf buf = Unpooled.buffer(16);
//		
//		while(buf.writableBytes() >= 4){
//			buf.writeInt(random.nextInt());
//		}
//		
//		while(buf.isReadable()){
//			System.out.println(buf.readInt());
//		}
		
		derivedBuffers();
	}
	
	/**
	 * 衍生的缓冲区
	 * 
	 * 调用duplicate()、slice()、slice(int index, int length)、order(ByteOrder endianness)会创建一个现有缓冲区的视图
	 */
	private static void derivedBuffers(){
		// get a Charset of UTF-8 01.
		Charset utf8 = Charset.forName("UTF-8");
		// get a ByteBuf 
		ByteBuf buf = Unpooled.copiedBuffer("Netty in Action rocks!", utf8); 
		// slice 
		ByteBuf sliced = buf.slice(0, 14);
		// copy 
		ByteBuf copy = buf.copy(0, 14); 
		// print "Netty in Action rocks!" 09.
		System.out.println(buf.toString(utf8));
		// print "Netty in Act" 11.
		System.out.println(sliced.toString(utf8));
		// print "Netty in Act" 13.
		System.out.println(copy.toString(utf8)); 
		
	}
}
